package com.yanqu.road.dao.impl.servercenter;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.recharge.RechargeOpenConfig;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RechargeOpenConfigDaoImpl extends TempDao {
    public Map<String, RechargeOpenConfig> getDataUploadInfo(int channelId) throws Exception {
        ResultSet rs = null;
        CallableStatement call = null;
       String sql = "select * from t_s_applets_recharge_switch where channelId = ?";
        Map<String, RechargeOpenConfig> map = new HashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, channelId);
            rs = call.executeQuery();
            while (rs.next()) {
                RechargeOpenConfig dataUploadInfo = new RechargeOpenConfig();
                dataUploadInfo.setLevel(rs.getInt("level"));
                dataUploadInfo.setRegion(rs.getString("region"));
                dataUploadInfo.setOpen(rs.getBoolean("regionSwitch"));
                List<Integer> list = new ArrayList<>();
                String timeSlot = rs.getString("timeSlot");
                String[] split = timeSlot.split(",");
                for (String s : split) {
                    String[] strings = s.split("-");
                    if (strings.length < 2) {
                        continue;
                    }
                    int min = Integer.parseInt(strings[0]);
                    int max = Integer.parseInt(strings[1]);
                    if (min > max) {
                        continue;
                    }
                    if (min < 0) {
                        continue;
                    }
                    if (max > 24) {
                        continue;
                    }
                    list.add(min);
                    list.add(max);
                }
                dataUploadInfo.setTimePeriodList(list);
                map.put(dataUploadInfo.getRegion(), dataUploadInfo);
            }
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
            throw e;
        } finally {
            getDb().closeConnection(call, rs);
        }
        return map;
    }
}
